"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 故障&可靠性测试
Case Name   : 主/备数据库节点表空间对应目录权限人为破坏（权限或目录丢失），主机执行建表语句语句
Create At   : 2020/07/20
@zou_jialiang0505328114
Description :
    1、启动主备数据库，判断数据库状态；
    2、主库上建立表空间（指定目录）；
    3、修改主库表空间目录权限；
    4、主机上执行指定表空间建表语句；
    5、还原权限
    6、修改备库表空间目录权限；
    7、主机上执行建表语句；
    8、查询数据库状态；
    9、重启恢复主备状态；
Expect      :
    1、启动成功，数据库状态正常
    2、执行成功
    3、执行成功
    4、执行失败
    5、执行成功
    6、执行成功
    7、执行失败
    8、备机stop
    9、执行成功
History     :
    2020/12/7 n@ningyali 1、优化脚本；2、teardown中增加主备机对表、表空间及表空间路径的删除
"""

import unittest

from yat.test import Node
from yat.test import macro

from testcase.utils.Common import Common
from testcase.utils.CommonSH import *
from testcase.utils.Logger import Logger

common = Common()


class Deletaduit(unittest.TestCase):
    commonshpri = CommonSH('PrimaryDbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Dbsys_Case140.py start------------')
        self.rootNode = Node()
        self.primary_user_node = Node(node='PrimaryDbUser')
        self.primary_root_node = Node(node='PrimaryRoot')
        self.standby1_root_node = Node(node='Standby1Root')
        self.standby1_user_node = Node(node='Standby1DbUser')
        self.standby2_root_node = Node(node='Standby2Root')
        self.t = int(time.time())
        self.tb_name = f"test{str(self.t)}"
        self.t_name = f"test{str(self.t)}"
        self.path = macro.DB_INSTANCE_PATH.split('/dn1')[0] + '/' + str(self.t)

    def test_startdb(self):
        # 主库上建立表空间（指定目录）；
        self.log.info('主库上建立表空间（指定目录）')
        self.sql = f'''drop tablespace if exists {self.tb_name}; create tablespace {self.tb_name} location '{self.path}';'''
        msg1 = self.commonshpri.executDbSql(self.sql)
        self.log.info(msg1)

        # 修改主库表空间目录权限
        self.log.info('修改主库表空间目录权限')
        self.log.info('chmod 000 ' + self.path)
        self.primary_user_node.sh('chmod 000 ' + self.path)

        # 主机上执行建表语句
        self.log.info('主机上执行建表语句')
        self.sql1 = f'''drop table if exists {self.t_name};CREATE TABLE {self.t_name}(i int) TABLESPACE {self.tb_name}'''
        msg3 = self.commonshpri.executDbSql(self.sql1)
        self.log.info(msg3)
        self.assertIn('Permission denied', msg3)

        # 主库恢复对应目录权限，备库删除目录权限
        self.log.info('主库恢复对应目录权限，备库删除目录权限')
        self.log.info('chmod 700 ' + self.path)
        self.primary_user_node.sh('chmod 700 ' + self.path)
        self.standby1_root_node.sh('chmod 000 ' + self.path)

        msg2 = self.commonshpri.executDbSql(self.sql1)
        self.log.info(msg2)

        # 查询数据库状态
        self.log.info('查询数据库状态')
        status = self.commonshpri.getDbClusterStatus('detail')
        self.log.info(status)
        self.assertIn('S Down    Manually stopped', status)
        self.standby1_root_node.sh('chmod 700 ' + self.path)

        is_started = self.commonshpri.startDbCluster()
        self.assertTrue(is_started)

    def tearDown(self):
        # 恢复目录权限
        self.primary_user_node.sh('chmod 700 ' + self.path)
        self.standby1_root_node.sh('chmod 700 ' + self.path)

        self.log.info("--------------------drop tablespace--------------------")
        cmd = f'''drop table if exists {self.t_name}; drop tablespace if exists {self.tb_name};'''
        self.log.info(cmd)
        msg = self.commonshpri.executDbSql(cmd)
        self.log.info(cmd)
        self.log.info(msg)

        shell_cmd = f"rm -rf {self.path}"
        self.log.info(shell_cmd)
        msg = self.primary_root_node.sh(shell_cmd).result()
        self.log.info(msg)
        msg = self.standby1_root_node.sh(shell_cmd).result()
        self.log.info(msg)
        msg = self.standby2_root_node.sh(shell_cmd).result()
        self.log.info(msg)
        self.log.info('---------------reliability_dbsys140.py finish----------------')
